﻿using UnityEngine;
using System.Net;
using System;
using System.IO;
public class TeachWebClient : MonoBehaviour {

    void Start () {
        WebClient client = new WebClient();
        client.DownloadDataCompleted += DownloadDataCallback;
        client.DownloadProgressChanged += Client_DownloadProgressChanged;

        string url = "http://pic4.nipic.com/20091113/2847083_105626034638_2.jpg";
        Uri uri = new Uri(url);
        client.DownloadDataAsync(uri);
    }
    //下载进度
    private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        Debug.Log(e.BytesReceived * 100 / e.TotalBytesToReceive  + "%");
    }
    //下载完成
    void DownloadDataCallback(object sender, DownloadDataCompletedEventArgs data)
    {
        try{
            if (data.Result.Length > 0 && data.Error == null && data.Cancelled == false)
            {
                using (MemoryStream ms = new MemoryStream(data.Result))
                {
                    byte[] buffer = ms.ToArray();
                    string path = @"D:\Unity-Teacher\Teach_TCP\Assets/iamge.png";
                    File.WriteAllBytes(path, buffer);
                    Debug.Log("下载完成");
                }
            }
        } catch (Exception exception){
            throw exception;
        }
    }
}
